<template>
    <div>
        <Modal v-model="data.isShow" :mask-closable="false" width="800">
            <p slot="header">
				<span>图片裁剪</span>
			</p>
			<div class="body">
                <div class="cropper-button">
                    <input type="file" id="input_select_img_file" @change="tirggerSelectFileAction" style="display: none">
                    <Button type="primary" @click="onClickSelectImg" class="btn">选取照片</Button>
                    <Button type="primary" @click="onClickCropStart" class="btn">开始裁剪</Button>
                    <Button type="primary" @click="onClickCropFinish" class="btn">完成</Button>
                </div>
                <!-- <img :src="cropperImg.img" style="width: 100px; height: auto;"> -->
                <div class="cropper-panel">
                    <vueCropper
                        ref="cropper"
                        :img="cropperImg.img"
                        :outputSize="cropperImg.outputSize"
                        :outputType="cropperImg.outputType"
                        :canScale="cropperImg.canScale"
                        :autoCrop="cropperImg.autoCrop"
                        :autoCropWidth="cropperImg.autoCropWidth"
                        :autoCropHeight="cropperImg.autoCropHeight"
                        :fixed="cropperImg.fixed"
                        :fixedNumber="cropperImg.fixedNumber"
                        :centerBox="true"
                        :infoTrue="cropperImg.infoTrue"
                        @realTime="realTime">
                    </vueCropper>
                </div>
			</div>
			<div slot="footer">
				<!-- <Button
					type="primary"
					size="large"
					:loading="data.isSubmitLoading"
					@click="handleSubmit()">
					{{data.actionType == 1 ? '新建' : '编辑'}}
				</Button> -->
			</div>
        </Modal>
        
    </div>
</template>

<script>
import {VueCropper} from 'vue-cropper'
import * as qiniu from 'qiniu-js'

import fileService from '@/network/service/FileService.js'

export default {
    components: {
        VueCropper
    },
    props: ['data'],
    data() {
        return {
            cropperImg: {
                img: '',
                outputSize: 1,
                outputType: 'jpeg',
                canScale: true,
                autoCrop: true,
                autoCropWidth: 750,
                autoCropHeight: 500,
                fixed: true,
                fixedNumber: [750, 500],
                //full: true,
                //original: true,
                infoTrue: false
            },
            qiniuConfig: {
                qiniuCDNUrl: null,
                qiniuLinkUrl: null,
                token: null
            }
        }
    },
    mounted() {
        this.init();
    },
    
    methods: {
        init() {

            // 获取服务器七牛
            let that = this;
            fileService.getQiNiuToken().then(res => {
                let result = res.data;
                let code = result.rescode;
                console.log();
                if (code == 100) {
                    that.qiniuConfig = result.data;
                }else {
                    console.log(result.msg);
                    that.$Message.error('发生异常，请重新打开此窗口');
                }
            }, error => {
                serviceException.netError(error);
                that.$Message.error('发生异常，请重新打开窗口');
            });

        },
        onClickSelectImg(){
            // 触发input-file文件上传控件事件 onClickSelectImg
            document.getElementById('input_select_img_file').click();
        },
        tirggerSelectFileAction : function (event,file) {
            var that = this;
            var file = event.target.files[0]; //name: "dangqi1.png" || type: "image/png"
            var type = file.type.split('/')[0];
            if ( type === 'image' ) {
                //将图片img转化为base64
                var reader = new FileReader();
                reader.readAsDataURL(file);
                reader.onloadend = function () {
                    var dataURL = reader.result;
                    // 图片回显 或者 上接口
                    that.cropperImg.img = dataURL;
                    //that.upload(blob); //执行上传接口

                    // 也可以将图片转 blob 对象 进行上传
                    //var blob = that.dataURItoBlob(dataURL);
                };
            } else {
                that.$Message.error('上传了非图片');
            }
        },
        dataURItoBlob (dataURI) {
            // base64 解码
            let byteString = window.atob(dataURI.split(',')[1]);
            let mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];
            let T = mimeString.split('/')[1];
            let ab = new ArrayBuffer(byteString.length);
            let ia = new Uint8Array(ab);
            for (let i = 0; i < byteString.length; i++) {
                ia[i] = byteString.charCodeAt(i);
            }
            return new Blob([ab], {type: mimeString});
        },
        
        handleUpload (file) {
            this.file = file;
            console.log(file);
            return false;
        },
        onClickCropStart() {
            // 开始截图
            this.$refs.cropper.startCrop();

            // this.$refs.cropper.getImgAxis();
            // // 获取图片基于容器的坐标点
            // let bb = this.$refs.cropper.getImgAxis();
            // console.log('获取图片基于容器的坐标点');
            // console.log(bb);
            // // 获取截图框基于容器的坐标点
            // let aa = this.$refs.cropper.getCropAxis();
            // console.log('获取截图框基于容器的坐标点');
            // console.log(aa);
            // // 截图框宽度
            // let w = this.$refs.cropper.cropW;
            // console.log("w:"+w);
            // // 截图框高度
            // let h = this.$refs.cropper.cropH;
            // console.log("h:"+h);
            // let x1 = aa.x1-bb.x1;
            // let y1 = aa.y1-bb.y1;
            // let x2 = x1 + w;
            // let y2 = y1 + h;
            // console.log("x1:"+x1.toFixed(0));
            // console.log("y1:"+y1.toFixed(0));
            // console.log("x2:"+x2.toFixed(0));
            // console.log("y2:"+y2.toFixed(0));

            // 停止截图
            this.$refs.cropper.stopCrop();
        },
        realTime(data){
            this.cropperImg.previews = data;
            //console.log(data);
        },
        onClickCropFinish(){
            let that = this;
            // this.$refs.cropper.getCropData(data => {
            //     // console.log(data);
            // });
            this.$refs.cropper.getCropBlob(data => {
                console.log(data);
                var img = window.URL.createObjectURL(data);
                console.log(img);
                // this.model = true;
                // this.modelSrc = img;
                that.uploadQiNiu(data);
            });
        },
        uploadQiNiu(data){
            let that = this;
            var putExtra = {
                fname: "images-icon",
                params: {},
                mimeType: [] || null
            };
            var config = {
                useCdnDomain: true,
                region: null
            };
            var observable = qiniu.upload(data, null, that.qiniuConfig.token, putExtra, config);
            var observer = {
                next(res){
                    // ...
                    console.log(res);
                },
                error(err){
                    // ...
                    console.log(err);
                    that.$Message.error('发生异常，请重新上传');
                }, 
                complete(res){
                    // {key: "sdfasdfasd", hash: "FiKrRIerHfDTpCWW9iQ9bvdxm-xr", bucket: "deao-car", fsize: 77101, imgW: 1162, …}
                    // ...
                    console.log(res);

                    let url = that.qiniuConfig.qiniuCDNUrl + res.key;

                    that.$emit('on-action-cropper-res', url);

                    that.data.isShow = false;

                    that.$Message.success('上传成功，请及时保存');
                }
            };
            var subscription = observable.subscribe(observer) // 上传开始
        }
    }
}
</script>

<style lang="less" scoped>
    .cropper-button {
        .btn {
            margin-right: 10px;
        }
    }
    .cropper-panel {
        width: 750px;
        height: 500px;
        margin-top: 5px;
    }
</style>


